import fs from 'fs'
import _ from 'lodash'
import { IO, map } from './util.js'

const readFile = function(fileName) {
    return new IO(function() {
        return fs.readFileSync(fileName, "utf-8")
    })
}

const print = function(x) {
    return new IO(function() {
        console.log(x)
        return x
    })
}

const cat = _.flowRight(map(print), readFile)

const v = cat("gulpfile.js")

console.log(v)

const x = v.unsafePerform().unsafePerform()
console.log("----------------------\n" + x)


console.log("------------------Use Join----------------")

const join = function(x) {x.join()}
v.join().unsafePerform()

console.log(`
通常来说，很容易遇见对一个返回 functor 的 f 进行 map 操作，这时候就有两层 Functor。
此时可以将这个行为抽象到 chain 函数里。
`)

const chain = _.curry(function(f, m) {
    return m.map(f).join()
})

const cat3 = _.flowRight(chain(print), readFile)
cat3("./README.md")